package com.example.broadcasttutital.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.broadcasttutital.R;

public class LocalBroadcastActivity extends AppCompatActivity {
    private IntentFilter intentFilter;
    private LocalBroadcastReceiver localReceiver;
    private LocalBroadcastManager localManager;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_broadcastreceiver);
        localManager = LocalBroadcastManager.getInstance(this);
        final Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getPackageName() + ".LOCAL_BROADCAST");
                localManager.sendBroadcast(intent);
                int dpi = getResources().getDisplayMetrics().densityDpi;
                Log.e("dpi","屏幕密度：" + dpi);
                float density = getResources().getDisplayMetrics().density;
                Log.e("density","density:" + density);
            }
        });

        final Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View v) {

            }
        });
        intentFilter = new IntentFilter();
        intentFilter.addAction(getPackageName() + ".LOCAL_BROADCAST");
        localReceiver = new LocalBroadcastReceiver();
        localManager.registerReceiver(localReceiver,intentFilter);
    }

    class LocalBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "received in local broadcast receiver", Toast.LENGTH_SHORT).show();
        }
    }
}
